<?php

namespace App\Http\Controllers\Api\Admin;

use App\Exceptions\OrderException;
use App\Express;
use App\Goods;
use App\OrderItem;
use App\Orders;
use App\UserInfo;
use App\UserIntegralRecord;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    public function changeOrderStatus(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereId($id)->first();
        if($thisOrder->status != 2)
            return response()->json(['level' => 'error','message' => '请保证订单为待发货状态']);

        if((!is_null($thisOrder->express_num) && $thisOrder->express_num != '') && (!is_null($thisOrder->express_time) && $thisOrder->express_time != '')){
            $thisOrder->status = 3;
            $thisOrder->save();
        }else{
            return response()->json(['level' => 'error','message' => '发货信息未完善']);
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisOrder]);
    }

    public function setShipInfo(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $expressNum  = !is_null($request->get('express_num')) ? $request->get('express_num') : '';
        $expressId  = !is_null($request->get('express_id')) ? $request->get('express_id') : '';
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereId($id)->first();
        if(!$thisOrder || ($thisOrder && $thisOrder->status != 2))
            return response()->json(['level' => 'error','message' => '该订单不存在或状态不正确']);

        /** @var Express $thisExpress */
        $thisExpress = Express::whereId($expressId)->first();
        if(!$thisExpress)
            return response()->json(['level' => 'error','message' => '快递公司不存在']);

        if($expressNum != '')$thisOrder->express_num   = $expressNum;
        $thisOrder->express_time = date('Y-m-d H:i:s',time());
        $thisOrder->express      = $thisExpress->name;
        $thisOrder->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisOrder]);
    }
}
